package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
@Api(tags = "套餐相关接口")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "套餐分页查询")
    public R<Page> page(int page, int pageSize, String name){
        log.info("套餐分页查询：page={},pageSize={},name={}",page,pageSize,name);
        //创建分页构造器
        Page<Setmeal> setmealPage = new Page(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<SetmealDto>(page, pageSize);

        //创建条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.like(name!=null,Setmeal::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        //调用方法
        setmealService.page(setmealPage,queryWrapper);

        //对象拷贝,忽略records属性
        //拷贝Setmeal基本属性给SetmealDto，对于结果列表 records属性，需要封装菜品分类名称，单独处理
        BeanUtils.copyProperties(setmealPage,setmealDtoPage,"records");
        //获取Dish的records属性
        List<Setmeal> records = setmealPage.getRecords();
        //将处理后的Setmeal的records集合赋值给SetmealDto的records
        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            Long categoryId = item.getCategoryId();//获取分类id
            Category category = categoryService.getById(categoryId);//通过id获取Category对象
            if (category != null) {
                String categoryName = category.getName();//通过Category对象获取分类名
                setmealDto.setCategoryName(categoryName);//将分类名给SetmealDto对象对应的属性设置值
            }
            return setmealDto;//返回处理结果d
        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(list);//将处理后的records给setmealPage页面设置值，使得前端能够显示该数据
        return  R.success(setmealDtoPage);
    }

    /**
     * 新增套餐，同时保存套餐和菜品的关系
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmeal",allEntries = true)
    @PostMapping
    @ApiOperation(value = "新增套餐")
    public R save(@RequestBody SetmealDto setmealDto){
        log.info("新增套餐数据，改套餐数据为：{}",setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐信息成功！");
    }

    /**
     * 根据id查询套餐信息，(用于数据回显)
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询套餐信息")
    public R<SetmealDto> list(@PathVariable Long id){
        log.info("修改套餐信息，数据回显：当前菜品id为：{}",id);
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        return R.success(setmealDto);
    }

    /**
     * 修改套餐数据，同时修改套餐菜品数据
     * @param setmealDto
     * @return
     */
    @PutMapping
    @ApiOperation(value = "修改套餐数据")
    @CacheEvict(value = "setmeal",allEntries = true)
    public R<String> update(@RequestBody SetmealDto setmealDto){
        log.info("修改套餐数据，该套餐信息为:{}",setmealDto);
        setmealService.updateWithDish(setmealDto);
        return R.success("套餐信息修改成功！");
    }

    /**
     * 根据ID 停售/启售（批量停售/批量启售) 套餐
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmeal",allEntries = true)
    @ApiOperation(value = "根据ID 停售/启售（批量停售/批量启售) 套餐")
    public R<String> updateMulStatus(@PathVariable Integer status,Long[] ids){
        log.info("停售/启售套餐信息id为：{}",ids);
        //将数组转换成集合
        List<Long> list = Arrays.asList(ids);
        //创建条件构造器
        LambdaUpdateWrapper<Setmeal> updateWrapper = new LambdaUpdateWrapper<>();
        //添加条件
        updateWrapper.in(Setmeal::getId,list).set(Setmeal::getStatus,status);

        //执行方法
        setmealService.update(updateWrapper);
        return R.success("套餐信息修改成功！");
    }

    /**
     * 根据ID 删除（批量删除) 套餐信息
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmeal",allEntries = true)
    @ApiOperation(value = "根据ID 删除（批量删除) 套餐信息")
    public R<String> remove(Long[] ids){
        log.warn("删除菜品的id为：{}",ids);
        //数组转换成集合
        List<Long> list = Arrays.asList(ids);
        //根据套餐状态，调用删除方法，若启售则不允许删除，若停售则可删除
        setmealService.remove(list);
        return R.success("删除套餐信息成功");
    }

    /**
     * 根据条件查询套餐数据
     * @return
     */
    @Cacheable(value = "setmeal",key = "#categoryId+':'+ #status")
    @ApiOperation(value = "根据条件查询套餐数据")
    @GetMapping("/list")
    public R<List<Setmeal>> list(Long categoryId,Integer status){
        log.info("categoryId={},status={}",categoryId,status);
        //创建条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(categoryId!=null,Setmeal::getCategoryId,categoryId);
        queryWrapper.eq(status!=null,Setmeal::getStatus,status);
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }

    /**
     * 查看套餐菜品信息
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    @ApiOperation(value = "查看套餐菜品信息")
    public R getDish(@PathVariable Long id){
        log.info("套餐id为：{}",id);
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        return R.success(setmealDishes);
    }

}
